package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 当前线程任务负责与指定的客户端进行交互.
 * 这里的交互规则要遵从HTTP协议的交互要求,以客户端进行"一问一答"的交互规则
 * 交互过程分为三大步
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            String path = request.getUri();
            System.out.println("抽象路径:" + path);

            //2处理请求

            //3发送响应
            //测试将resources/static目录下的index.html页面响应给浏览器
            /*
                类加载路径:包含我们所有java包的目录就是类加载路径
                这里就是:target/classes
                定位类加载路径的代码:
                任何当前项目中的类的类名.class.getClassLoader.getResource(".")
             */
            File root = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir = new File(root, "static");
            /*
                http://localhost:8088/classtable.html
                http://localhost:8088/index.html
             */
            File file = new File(staticDir, path);
            /*
                发送一个响应
                HTTP/1.1 200 OK(CRLF)
                Content-Type: text/html(CRLF)
                Content-Length: 2546(CRLF)(CRLF)
                1011101010101010101......
             */
            //1发送状态行
            println("HTTP/1.1 200 OK");
            //2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            //单独发送空行表示响应头部分发送完毕
            println("");
            //3发送响应正文
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[1024*10];
            int len;
            while((len = fis.read(buf))!=-1){
                out.write(buf,0,len);
            }


        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //HTTP协议要求交互完毕要断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

   private void println(String line) throws IOException {
       OutputStream out = socket.getOutputStream();
       byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
       out.write(data);
       out.write(13);
       out.write(10);
   }


}







